#!/usr/bin/env python2.7

import sys
import os
from gbconf import GBConfig


def usage(app):
    sys.stdout.write("usage: %s start|stop [-b BIND] [-h]\n"
               "-b\tBind address and port (default: 0.0.0.0:8800).\n"
               "-h\tPrint usage message.\n"%(app))


def stop():
    try:
        with open(GBConfig.pid, "r") as fp:
            pid = fp.readline()
            import signal
            os.killpg(int(pid), signal.SIGKILL)
    except Exception as e:
        sys.stderr.write(e.message)


def start(args):
    try:
        logfp = os.open(GBConfig.log, os.O_CREAT | os.O_APPEND | os.O_RDWR, 0)
        sys.stderr.close()
        sys.stdin.close()
        sys.stdout.close()

        os.dup2(logfp, 0)
        os.dup2(logfp, 1)
        os.dup2(logfp, 2)

        os.close(logfp)
        pid = os.fork()
        if pid == 0:
            pid = os.getpid()
            os.setpgid(pid, pid)
            with open(GBConfig.pid, "w") as fp:
                fp.write("%d"%(pid))
            os.execve("./manage.py", ["./manage.py", "runserver", GBConfig.bind], os.environ)
            sys.exit(-1)
        elif pid > 0:
            os.close(0)
            os.close(1)
            os.close(2)
            sys.exit(0)
    except Exception as e:
        sys.stderr.write(e.message)
        sys.exit(-1)


if sys.argv[1] == "start":
    stop()
    start(sys.argv[2:])
elif sys.argv[1] == "stop":
    stop()
else:
    usage(sys.argv[0])
